package org.example;

public class ArraysDemo {

    public static void main(String[] args) {
        // 稀疏数组
        int[][] origin = new int[11][11];

        // 初始化值
        origin[1][2] = 1;
        origin[2][3] = 2;

        // 转换为稀疏数组

        // 计算非零个数
        int count = 0;
        for (int i = 0; i < origin.length; i++) {
            for (int j = 0; j < origin[i].length; j++) {
                if (origin[i][j] != 0) {
                    count ++;
                }
            }
        }

        // 初始化稀疏数组
        int[][] sparse = new int[count + 1][3];
        sparse[0][0] = origin.length;
        sparse[0][1] = origin[0].length;
        sparse[0][2] = count;

        // 记录当前稀疏数组记录的行
        int index = 1;
        for (int i = 0; i < origin.length; i++) {
            for (int i1 = 0; i1 < origin[i].length; i1++) {
                if (origin[i][i1] != 0) {
                    sparse[index][0] = i;
                    sparse[index][1] = i1;
                    sparse[index][2] = origin[i][i1];
                    index ++;
                }
            }
        }

        // 打印原数组
        System.out.println("原数组：");
        for (int i = 0; i < origin.length; i++) {
            for (int i1 = 0; i1 < origin[i].length; i1++) {
                System.out.printf("%d\t", origin[i][i1]);
            }
            System.out.println();
        }

        System.out.println("稀疏数组：");
        for (int i = 0; i < sparse.length; i++) {
            System.out.printf("%d\t%d\t%d\n", sparse[i][0], sparse[i][1], sparse[i][2]);
        }

        // 将稀疏数组转换为原数组
        int[][] newOrigin = new int[sparse[0][0]][sparse[0][1]];
        for (int i = 1; i < sparse.length; i++) {
            for (int i1 = 0; i1 < sparse[i].length; i1++) {
                newOrigin[sparse[i][0]][sparse[i][1]] = sparse[i][2];
            }
        }

        // 打印转换回来的原数组
        System.out.println("转换后的原数组：");
        for (int i = 0; i < newOrigin.length; i++) {
            for (int i1 = 0; i1 < newOrigin[i].length; i1++) {
                System.out.print(newOrigin[i][i1] + "\t");
            }
            System.out.println();
        }
    }
}
